<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >

      <template slot-scope="scope" slot="menu">
        <el-button
          icon="el-icon-picture-outline"
          size="small"
          type="text"
          @click.stop="getPreview(scope.row.rqUrl)">查看二维码
        </el-button>
        <el-button
          icon="el-icon-download"
          size="small"
          type="text"
          v-preventClick
          @click.stop="downloadImage(scope.row)">下载二维码
        </el-button>
      </template>
      <template slot="menuLeft">
        <!-- <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click.stop="handleSave"
        >新 增
        </el-button
        > -->
        <!-- <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permission.qrcode_delete"
          @click="handleDelete"
        >删 除
        </el-button> -->
      </template>
      
      <template slot-scope="{row}" slot="isOn">
        <el-switch
          :active-value="1"
          :inactive-value="0"
          active-color="#13ce66"
          v-model="row.isOn"
          @change="handleSwitch(row)">
        </el-switch>
      </template>
    </avue-crud>
    <el-image-viewer
        style="z-index: 2048"
        v-if="payVoucherDialog"
        :on-close="()=>{ payVoucherDialog = false }"
        :url-list="[rqUrlImage]"
      ></el-image-viewer>
    <el-dialog
      :title="dialogText"
      top="1%"
      width="1000px"
      append-to-body
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      @close="close"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <qrcodeForm :codeForm="codeForm" :payLogoList="payLogoList" ref="toQRCodeForm"></qrcodeForm>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" v-preventClick @click="qrcodeSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import {
  getList,
  getDetail,
  add,
  remove, qrcodeDownload, updateIsOn,
} from "@/api/rb-service/qrcode/qrcode";
import {mapGetters} from "vuex";
import {getToken} from "@/util/auth";
import qrcodeForm from "@/components/rb-service/qrcode-form";
import {downloadFileAxiosBase64} from "@/util/util";//downloadFileBase64

export default {
  props: {
    rqBatchNumber: {
      type: String
    }
  },
  components: {
    qrcodeForm,
    ElImageViewer
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      dialogVisible: false,
      dialogType: "",
      dialogText: "新增二维码",
      rqUrlImage: '',
      payVoucherDialog: false,
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      codeForm: {},
      payLogoList: [],
      // codeData: {
      //   bottomLogo1: "C:\\Users\\admin\\Desktop\\test\\花呗.png",
      //   bottomLogo1X: "417",
      //   bottomLogo1Y: "1746",
      //   bottomLogo2: "C:\\Users\\admin\\Desktop\\test\\京东.png",
      //   bottomLogo2X: "545",
      //   bottomLogo2Y: "1746",
      //   bottomLogo3: "C:\\Users\\admin\\Desktop\\test\\图层.png",
      //   bottomLogo3X: "669",
      //   bottomLogo3Y: "1746",
      //   bottomLogo4: "C:\\Users\\admin\\Desktop\\test\\微信支付.png",
      //   bottomLogo4X: "792",
      //   bottomLogo4Y: "1746",
      //   bottomLogo5: "C:\\Users\\admin\\Desktop\\test\\支付宝.png",
      //   bottomLogo5X: "915",
      //   bottomLogo5Y: "1746",
      //   contentX: "354",
      //   contentY: "1650",
      //   isOn: 1,
      //   number: 1,
      //   phone: "17887926215",
      //   phoneX: "537",
      //   phoneY: "1950",
      //   qrCodeUrlX: "347",
      //   qrCodeUrlY: "467",
      //   qrCodeX: "480",
      //   qrCodeY: "1200",
      //   word: "请扫码支付",
      // },
      option: {
        height: "auto",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        selection: true,
        searchMenuSpan: 6,
        columnBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        searchLabelWidth:120,
        column: [
          {
            label: "批次号",
            prop: "rqBatchNumber",
            search: true,
            overHidden:true,
            width:100
          },
          {
            label: "二维码编号",
            prop: "rqCode",
            search: true,
            overHidden:true,
            minWidth:100
          },
          {
            label: "二维码状态",
            prop: "isOn",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=is_on",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            value: "1",
            dataType: "string",
            showColumn: false,
            search: false,
            overHidden:true,
            minWidth:100
          },
          {
            label: "是否绑定商户",
            prop: "rpiNo",
            search: false,
            overHidden:true,
            minWidth:100
          },
          {
            label: "二维码链接",
            prop: "urls",
            search: false,
            overHidden:true,
            minWidth:250
          },
          // {
          //   label: "租户名称",
          //   prop: "tenantName",
          //   search: true,
          // },
          {
            label: "创建人名称",
            prop: "realName",
            search: true,
            overHidden:true,
            minWidth:180
          },
          {
            label: "创建时间",
            prop: "createTime",
            search: false,
            overHidden:true,
            minWidth:140
          },
        ],
      },
      data: [],
      codeBody: "",
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-service/service/qrcode/qrcode/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.qrcode_add, false),
        viewBtn: this.vaildData(this.permission.qrcode_view, false),
        delBtn: this.vaildData(this.permission.qrcode_delete, false),
        editBtn: this.vaildData(this.permission.qrcode_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  methods: {
    qrcodeSubmit() {
      //console.log(this.$refs.toQRCodeForm.payLogoList, 'this.$refs.toQRCodeForm.payLogoList')
      this.dialogVisible = false;
      if (this.$refs.toQRCodeForm.payLogoList[0].img) {
        this.codeForm.bottomLogo1 = this.$refs.toQRCodeForm.payLogoList[0].img
      }
      if (this.$refs.toQRCodeForm.payLogoList[1].img) {
        this.codeForm.bottomLogo2 = this.$refs.toQRCodeForm.payLogoList[1].img
      }
      if (this.$refs.toQRCodeForm.payLogoList[2].img) {
        this.codeForm.bottomLogo3 = this.$refs.toQRCodeForm.payLogoList[2].img
      } /*else if (this.$refs.toQRCodeForm.payLogoList[3].img) {
        this.codeForm.bottomLogo4 = this.$refs.toQRCodeForm.payLogoList[3].img
      } else if (this.$refs.toQRCodeForm.payLogoList[4].img) {
        this.codeForm.bottomLogo5 = this.$refs.toQRCodeForm.payLogoList[4].img
      }*/
      const form = {
        "bottomLogo1": this.codeForm.bottomLogo1,
        "bottomLogo2": this.codeForm.bottomLogo2,
        "bottomLogo3": this.codeForm.bottomLogo3,
        "bottomLogo4": this.codeForm.bottomLogo4,
        "bottomLogo5": this.codeForm.bottomLogo5,
        "isOn": this.codeForm.isOn,
        "number": this.codeForm.number,
        "phone": this.codeForm.phone,
        "word": this.codeForm.word,
        "middleLogo": this.codeForm.qrcodeLogo || ''
      }
      add(form).then((res) => {
          if (res.data.code == "200") {
            this.dialogVisible = false;
            this.onLoad(this.page);
            this.$refs.toQRCodeForm.$refs.uploadQRcodeLogo.clearFiles()
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            if(this.codeForm.number != 1){
              qrcodeDownload().then(res => {
                downloadFileAxiosBase64(res)
              })
            }


            //this.Download()
          }
        },
        (error) => {
          window.console.log(error);
        }
      );
    },
    /**
     * @func 开关
     * @desc 二维码开关 禁用启用
     * @param {Object} row - 商户信息
     * */
    handleSwitch(row) {
      updateIsOn(row.id, row.isOn).then((res) => {
        if(res.data.code !== 200 ){
          row.isOn = row.isOnCustom;
         }
      },(error) => {
        row.isOn = row.isOnCustom;
        window.console.log(error);
      });
    },
    handleSave() {
      /* 初始化 支付公司logo */
      this.codeForm = {
        number: "",
        isOn: "1",
        bottomLogoTypeList: [
          {bottomLogoType: 1, compList: []},
          {bottomLogoType: 2, compList: []},
          {bottomLogoType: 3, compList: []},
          { bottomLogoType: 4 , compList: [] },
          { bottomLogoType: 5 , compList: [] },
        ],
        bottomLogo1: '',
        bottomLogo2: '',
        bottomLogo3: '',
        bottomLogo4: '',
        bottomLogo5: '',
        phone: "",
        word: "请扫码支付",
        qrcodeLogo: "",
        firmLogo: "",
      };
      this.payLogoList = [
        {id: 1, img: ""},
        {id: 2, img: ""},
        {id: 3, img: ""},
        { id: 4, img: "" },
        { id: 5, img: "" },
      ],
        this.dialogVisible = true;
      this.dialogType = "add";
      this.dialogText = "新增二维码";
      this.$nextTick(() => {
        this.$refs.toQRCodeForm.getPhone();
        this.$refs.toQRCodeForm.getPayList();
      })
    },
    handleClose(done) {
      this.$refs.toQRCodeForm.$refs.uploadQRcodeLogo.clearFiles()
      done();
    },
    getPreview(url) {
      this.rqUrlImage = url;
      this.payVoucherDialog = true;
    },
    downloadImage(row) {
      var newUrl = row.rqUrl.replace('http','https');
      window.location.href = newUrl
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query,{rqBatchNumber: this.rqBatchNumber})
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        // this.data = data.records;
        this.data = data.records.map((item) => {
          item.isOnCustom = item.isOn;
          return item
        });
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      let exQuery = ``;
      exQuery += `&rqCode=${this.search.rqCode}`;
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.open(
          `/api/rb-service/service/qrcode/qrcode/export?${this.website.tokenHeader}=${getToken()}` + exQuery
        );
      });
    },
    handleTemplate() {
      window.open(
        `/api/rb-service/service/qrcode/qrcode/export-template?${this.website.tokenHeader}=${getToken()}`
      );
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>

<style>
</style>
